<template>
    <div>
        <div>
            <div v-for="(p,i) in arr" :key="i">
                <div v-if="p.user == user " class="right">
                    <div class="txt">{{p.txt}}</div>
                    <div class="tx">
                        <img :src="p.img" style="width:100%;border-radius:50%"/>
                        <span>{{p.user}}</span>
                    </div>
                </div>
                <div v-else class="left">
                    <div class="tx">
                        <img :src="p.img" style="width:100%;border-radius:50%"/>
                        <div>{{p.user}}</div>    
                    </div>
                    <div class="txts"> {{p.txt}}</div>
                </div>
            </div>
        </div>
        <div class="inp">
            <el-input v-model="txt"></el-input><el-button type="primary" @click="fs">发送</el-button>
        </div>
    </div>
</template>

<script>
export default {
    data(){
        return{
            arr:[],
            user:'',
            txt:'',
            img:'',
            scoket:{}
        }
    },
    created(){
        this.obj=this.$route.params.obj,
        this.user=JSON.parse(localStorage.getItem('UserInfo')).nickName
        this.img=JSON.parse(localStorage.getItem('UserInfo')).imgUrl
    },
    mounted(){
        this.scoket = new WebSocket('ws:localhost:8888');
        //开始连接
        this.scoket.onopen=function(){
            console.log('链接打开')
        }.bind(this)
        //接收信息
        this.scoket.onmessage=function(data){
            this.arr.push(JSON.parse(data.data))
        }.bind(this)
    },
    methods:{
        fs(){
            let obj={
                user:this.user,
                txt:this.txt,
                img:this.img
            }
            this.scoket.send(JSON.stringify(obj))
            this.txt=''
        }
    }
}
</script>

<style lang='scss' scoped>
.inp{
    width: 100%;
    position: fixed;
    bottom: 5%;
    .el-input{
        width: 80%;
    }
    .el-button{
        width: 20%;
    }   
}
.right{
    right: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
.left{
    left: 0;
    display: flex;
    align-items: center;
    justify-content: flex-start; 
}
.tx{
    width: 10%;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 10px;
}
.txt{
    border: 1px solid black;
    margin-right: 3%;
    border-radius: 10px;
    box-shadow: 1px 1px ;
    padding: 2%;
    background-color: rgba(0, 0, 255, 0.61);
}
.txts{
    border: 1px solid black;
    margin-left: 3%;
    border-radius: 10px;
    box-shadow: 1px 1px ;
    padding: 2%;
}
</style>